﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using XiaoYuStock.Model.Models;
using XiaoYuStock.AppService.State;
using XiaoYuStock.Core;
namespace XiaoYuStock.AppService.Storage
{
    public class StorageFile : IStorage
    {
        /// <summary>
        /// 存储分析结果
        /// </summary>
        /// <param name="state"></param>
        /// <param name="shareCode"></param>
        public void Save(AnalysedState state, string shareCode)
        {
            WriteFile(state.FileName, shareCode);
        }

        /// <summary>
        /// 写数据到文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="content"></param>
        private void WriteFile(string fileName, string content)
        {
            FileStream fs = new FileStream(fileName, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.WriteLine(content);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
        }


        /// <summary>
        /// 读数据到文件
        /// </summary>
        /// <param name="fileName"></param>
        private string ReadFile(string fileName)
        {
            string content = string.Empty;
            using (StreamReader sr = new StreamReader(fileName, System.Text.Encoding.GetEncoding("utf-8")))
            {
                content = sr.ReadToEnd().ToString();
                sr.Close();

            }
            return content;
        }

        /// <summary>
        /// 从指定设备中获取内容
        /// </summary>
        /// <param name="currentTime"></param>
        /// <returns></returns>
        public string GetContent(DateTime currentTime)
        {
            string stmp = System.Reflection.Assembly.GetExecutingAssembly().Location;
            stmp = stmp.Substring(0, stmp.LastIndexOf('\\'));
            stmp = Path.Combine(stmp, "data", currentTime.ToString("yyyy-MM-dd"));
            if (!Directory.Exists(stmp))
            {
                LogHelper.ErrorAsync(string.Format("没有要发送的邮件内容,{0}", stmp));
                return string.Empty;
            }
            var files = Directory.GetFiles(stmp);
            string title = currentTime.ToString("yyyy-MM-dd") + "数据分析";
            StringBuilder stb = new StringBuilder();
            if (files.Any())
            {
                foreach (var f in files)
                {
                    stb.AppendLine(System.IO.Path.GetFileName(f));
                    stb.AppendLine(ReadFile(f));
                    stb.AppendLine(" ");
                    stb.AppendLine(" ");
                }
            }
            return stb.ToString();
        }
    }
}
